package com.ithiema.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ithiema.reggie.Service.UserService;
import com.ithiema.reggie.common.R;

import com.ithiema.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/sendMsg")
    //接收前段传来的数据,两个用Map
    private R<String> sendMsg(@RequestBody Map<String,String> map, HttpSession session){
        //1.随机生成验证码   调用生成验证码的方法  转为string类型
        String code = "1234";
        //2.获取手机号
        String phone = map.get("phone");

    //需要将生成的验证码保存到Redis,设置过期时间
        redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);

//        //3.将验证码存入session
//        session.setAttribute(phone,code);


        //4.返回验证码
        return R.success("验证码发送成功");
    }

    //登录手机端
    @PostMapping("/login")
    private R<User> login(@RequestBody Map<String,String> map, HttpSession session){

        String code = map.get("code");
        String phone = map.get("phone");


    //从Redis中获取验证码   通过手机号获取到验证码{因为是键值对}
        Object sessioncode = redisTemplate.opsForValue().get(phone);


//        //获取用户输入的验证码
//        String sessioncode = (String) session.getAttribute(phone);

        if (sessioncode != null && sessioncode.equals(code)){
        //下一步根据用户是不是新用户,需要查询数据库
        LambdaQueryWrapper<User> qq = new LambdaQueryWrapper<>();
        qq.eq(User::getPhone,phone);
        User user = userService.getOne(qq);
        //如果是新用户，添加到数据（注册）
        if (user==null){
            user = new User();
            user.setPhone(phone);
            //添加状态
            user.setStatus(1);
            //添加到userService
            userService.save(user);
        }


   //因为在 Redis 中所以需要在Redis中移除
            redisTemplate.delete(phone);

//        //5. 登陆成功，把session中的验证码移除
//        session.removeAttribute(phone);



        //将用户的id存入session
        session.setAttribute("user",user.getId());
        return R.success(user);
        }
        return R.error("验证码输入错误");
    }


    //手机端退出登录
    @PostMapping("/loginout")
    private R<String> tui(HttpSession session){
        //id存在session 后面name是key根据存session时间填写的key
        session.removeAttribute("user");

        return R.success("成功退出");
    }
}
